package com.ricky.room.flow

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.room.Room
import com.ricky.room.databinding.ActivityMainBinding
import com.ricky.room.db.User
import com.ricky.room.db.UserDataBase
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.lang.Exception

class FlowRoomActivity : AppCompatActivity(), CoroutineScope by MainScope() {
    private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val dataBase: UserDataBase by lazy {
        Room.databaseBuilder(this, UserDataBase::class.java, "user.db").build()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnInsert.setOnClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    dataBase.userFlowDao().insertUser(createUser())
                }
                Toast.makeText(this@FlowRoomActivity, "Insert success", Toast.LENGTH_SHORT).show()
            }
        }
        binding.btnDelete.setOnClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    dataBase.userFlowDao().deleteUser(createUser().copy(id = getUid()))
                }
                Toast.makeText(this@FlowRoomActivity, "Delete success", Toast.LENGTH_SHORT).show()
            }
        }
        updateView()
    }

    private fun getUid(): Long {
        return try {
            binding.etId.text.toString().toLong()
        } catch (e: Exception) {
            0L
        }
    }

    private fun createUser(): User {
        val name = binding.etName.text.toString()
        val gender = binding.etGender.text.toString()
        val age = binding.etAge.text.toString()
        return User(name = name, gender = gender, age = age)
    }

    // 使用Flow监听数据库，数据改变自动更新UI
    private fun updateView(){
        dataBase.userFlowDao().queryAllUser().onEach { users ->
            val text = users.joinToString("\n") { "${it.id}-${it.name} ${it.gender} ${it.age}" }
            binding.tvInfo.text = text
        }.launchIn(this)
    }
}